import { createWebHashHistory, createRouter } from 'vue-router'

import Layout from '../views/Main.vue'
import Login from '../views/Login/index.vue'


// const localData = localStorage.getItem('pz_v3pz')
const routes = [
  {
    path: '/',
    component: Layout,
    name: 'main',
    redirect: () => {
      const token = localStorage.getItem('pz_token')
      if (!token) {
        return '/login'
      }
      // 获取本地存储中的路由配置
      const localData = JSON.parse(localStorage.getItem('pz_v3pz'));

      // 如果有可用路由，跳转到第一个
      if (localData) {
        if (localData.menu.routerList[0].children) {
          const child = localData.menu.routerList[0].children
          return child[0].meta.path
        } else {
          return localData.menu.routerList[0].meta.path
        }
      }
      // 没有可用路由时，默认跳转到根路径（会触发路由守卫）
      return '/';
    },
  },
  {
    path: '/login',
    component: Login
  },
]


const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

//全局路由守卫
router.beforeEach((to, from) => {
  const token = localStorage.getItem('pz_token')
  if (!token && to.path !== '/login') {
    return '/login'
  } else if (token && to.path === '/login') {
    return '/'
  } else {
    //允许当前路由跳转
    return true
  }

})

export default router